<template>
  <div>
    <!-- 上传组件 -->
    <el-upload
      action="http://back1.idcfengye.com:15173/competition/uploadDocument"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="beforeUpload"
      :headers="headers"
      accept=".pdf,.doc,.docx"
      multiple
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip">只能上传 pdf, doc, docx 文件，且不超过 500MB</div>
    </el-upload>
    <el-table :data="documents">
      <el-table-column prop="id" label="文序号" width="80"></el-table-column>
      <el-table-column prop="filepath" label="文件链接">
        <template #default="row">
          <a :href="`${uploadUrl}${row.row.filepath}`" target="_blank">{{ row.row.filepath }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="操作" width="300">
        <template #default="row">
          <el-button type="success" @click="addDocument(row.row.id)">启用</el-button>
          <el-button type="danger" @click="deleteDocument(row.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const documents = ref();
const uploadUrl = ref('http://back1.idcfengye.com:15173');

const headers = ref({
  'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
});

//启用文件
async function addDocument(id){
  try{
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/enableDocument/${id}`, {
          headers:{
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
          } 
    })
    getDocuments();
    
  }catch(error){
    console.log(error);
  }
  ElMessage.success('启用成功');
}


// 删除 '/upload/' 的函数
function removeUploadPath(filePath) {
  return filePath.replace('/documents/', '');
}

//删除文件
async function deleteDocument(row){
   const filename = removeUploadPath(row.filepath)
  try{
    const response = await axios.delete(`http://back1.idcfengye.com:15173/competition/deleteDocument/delete/${filename}/${row.id}`,{ 
      headers:{
        'Authorization':`Bearer ${localStorage.getItem('adminToken')}`
      }
    })
    console.log(response);
    
    ElMessage.success('删除成功');
  }catch(error){
    if(error.response){
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
      ElMessage.error('删除失败，状态码：' + error.response.status);
    } else if (error.request){
      console.log(error.request);
      ElMessage.error('删除失败，请求已发出但没有收到响应');
    } else {
      console.log('Error', error.message);
      ElMessage.error('删除失败：' + error.message);
    }
  }
}

// 获取文档列表
const getDocuments = async () => {
  try{
    const response = await axios.get('http://back1.idcfengye.com:15173/competition/documents', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
      }
    })
    documents.value = response.data.documents;
  }catch(error){
    console.log(error);
  }
};

// 上传成功后的回调函数
const handleSuccess = (response) => {
  ElMessage.success(response.msg);
};

// 上传失败后的回调函数
const handleError = (error) => {
  ElMessage.error(error.message);
};

// 在组件挂载后获取文档列表
const beforeUpload = (file) => {
  // 检查文件类型和大小的逻辑
  const isAcceptableType = ['.pdf', '.doc', '.docx'].includes(file.name.slice(file.name.lastIndexOf('.')));
  const isAcceptableSize = file.size / 1024 / 1024 < 500; // 限制文件大小不超过500MB

  if (!isAcceptableType) {
    ElMessage.error('不支持的文件类型');
    return false;
  }
  if (!isAcceptableSize) {
    ElMessage.error('文件大小不能超过500MB');
    return false;
  }
  return true;
};

onMounted(() => {
  getDocuments();
})
</script>

<style scoped>
/* 可以在这里添加一些自定义样式 */
</style>
